package logic

import (
	"context"
	"errors"
	"person/models/mysql"
	"person/pkg"

	"person/wechatrpc/internal/svc"
	"person/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *wechatrpc.UserLoginRequest) (*wechatrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	var weChat mysql.WeChat
	if in.LoginType == 1 {
		err := weChat.FindWeChatByTel(mysql.DB, in.Tel)
		if err != nil {
			return nil, err
		}
		if weChat.ID == 0 {
			return nil, errors.New("用户不存在")
		}
		if in.LoginType == 1 {
			if pkg.Md5(in.Password) != weChat.Password {
				return nil, errors.New("密码不正确")
			}
		}
	} else if in.LoginType == 2 {
		err := weChat.FindWeChatByAccount(mysql.DB, in.Qq, in.Email, in.WaChatCode)
		if err != nil {
			return nil, errors.New("qq/邮箱/微信号不存在")
		}
		if pkg.Md5(in.Password) != weChat.Password {
			return nil, errors.New("密码不正确")
		}
	} else {
		return nil, errors.New("当前暂不支持此方式登录")
	}

	/*
		登录:
				验证用户是否存在 根据手机号

				设置loginType  1. 手机号+密码
							  2. qq/邮箱/微信号+密码

					验证码缓存  密码

				登录成功
	*/

	return &wechatrpc.UserLoginResponse{
		UserId: int64(weChat.ID),
	}, nil
}
